package com.ryder.ryderschool.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ryder.ryderschool.entity.Project;
import com.ryder.ryderschool.entity.ProjectFunding;
import com.ryder.ryderschool.entity.User;
import com.ryder.ryderschool.mapper.ProjectFundingMapper;
import com.ryder.ryderschool.service.ProjectFundingService;
import com.ryder.ryderschool.service.ProjectService;
import com.ryder.ryderschool.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class ProjectFundingServiceImpl extends ServiceImpl<ProjectFundingMapper, ProjectFunding> implements ProjectFundingService {

    private final ProjectService projectService;
    private final UserService userService;

    @Override
    @Transactional
    public void createFunding(ProjectFunding funding) {
        // 检查项目是否存在
        Project project = projectService.getById(funding.getProjectId());
        if (project == null) {
            throw new RuntimeException("项目不存在");
        }

        // 检查是否是项目负责人
        User currentUser = userService.getCurrentUser();
        if (!currentUser.getId().equals(project.getLeaderId())) {
            throw new RuntimeException("只有项目负责人可以创建资金记录");
        }

        // 设置初始状态为待审批
        funding.setStatus("待审批");
        save(funding);
    }

    @Override
    @Transactional
    public void updateFunding(ProjectFunding funding) {
        ProjectFunding existingFunding = getById(funding.getId());
        if (existingFunding == null) {
            throw new RuntimeException("资金记录不存在");
        }

        // 检查是否是项目负责人
        Project project = projectService.getById(existingFunding.getProjectId());
        User currentUser = userService.getCurrentUser();
        if (!currentUser.getId().equals(project.getLeaderId())) {
            throw new RuntimeException("只有项目负责人可以修改资金记录");
        }

        // 只能修改待审批状态的记录
        if (!"待审批".equals(existingFunding.getStatus())) {
            throw new RuntimeException("只能修改待审批状态的资金记录");
        }

        updateById(funding);
    }

    @Override
    @Transactional
    public void deleteFunding(Integer id) {
        ProjectFunding funding = getById(id);
        if (funding == null) {
            throw new RuntimeException("资金记录不存在");
        }

        // 检查是否是项目负责人
        Project project = projectService.getById(funding.getProjectId());
        User currentUser = userService.getCurrentUser();
        if (!currentUser.getId().equals(project.getLeaderId())) {
            throw new RuntimeException("只有项目负责人可以删除资金记录");
        }

        // 只能删除待审批状态的记录
        if (!"待审批".equals(funding.getStatus())) {
            throw new RuntimeException("只能删除待审批状态的资金记录");
        }

        removeById(id);
    }

    @Override
    public ProjectFunding getFunding(Integer id) {
        return getById(id);
    }

    @Override
    public Page<ProjectFunding> listFundings(Integer projectId, Integer pageNum, Integer pageSize) {
        return page(new Page<>(pageNum, pageSize),
                new LambdaQueryWrapper<ProjectFunding>()
                        .eq(ProjectFunding::getProjectId, projectId)
                        .orderByDesc(ProjectFunding::getCreatedAt));
    }

    @Override
    @Transactional
    public void approveFunding(Integer id, boolean approved, String comment) {
        ProjectFunding funding = getById(id);
        if (funding == null) {
            throw new RuntimeException("资金记录不存在");
        }

        // 检查用户权限（院系管理员或科研处管理员）
        User currentUser = userService.getCurrentUser();
        if (!"院系管理员".equals(currentUser.getRole()) && !"科研处管理员".equals(currentUser.getRole())) {
            throw new RuntimeException("只有管理员可以审批资金记录");
        }

        // 检查项目所属院系
        Project project = projectService.getById(funding.getProjectId());
        if ("院系管理员".equals(currentUser.getRole()) && !currentUser.getDeptId().equals(project.getDeptId())) {
            throw new RuntimeException("只能审批本院系的资金记录");
        }

        // 更新状态
        funding.setStatus(approved ? "已通过" : "已驳回");
        if (comment != null && !comment.isEmpty()) {
            funding.setComment(comment);
        }
        updateById(funding);
    }
} 